package com.habdqn.studentmanager.util;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;

import com.habdqn.studentmanager.bean.Teacher;
import com.habdqn.studentmanager.constant.Constant;

/**
 * @author Fan
 * 
 *         2017年5月9日 工程工具类
 * 
 */
public class ProjectUtil {

	/**
	 * 保存每个请求的Request对象
	 */
	private static ThreadLocal<HttpServletRequest> requests = new ThreadLocal<>();

	/**
	 * 保存每个请求的Response对象
	 */
	private static ThreadLocal<HttpServletResponse> responses = new ThreadLocal<>();

	/**
	 * 保存每个请求的Session对象
	 */
	private static ThreadLocal<HttpSession> sessions = new ThreadLocal<>();
	
	/**
	 * 保存当前项目的servletContext
	 */
	private static ServletContext servletContext = null;
	
	/**
	 * 设置当前项目的servletContext
	 * @param servletContext
	 */
	public static void setServletContext(ServletContext servletContext ) {
		
		if (null != ProjectUtil.servletContext) {
			return ;
		}
		
		ProjectUtil.servletContext = servletContext;
	}
	
	/**
	 * 获取当前项目的ServletContext
	 * 
	 * @return
	 */
	public static ServletContext getServletContext() {
		return servletContext;
	}

	/**
	 * @return the requests
	 */
	public static HttpServletRequest getRequests() {
		return requests.get();
	}

	/**
	 * @param requests
	 *            the requests to set
	 */
	public static void setRequests(HttpServletRequest request) {
		requests.set(request);
		sessions.set(request.getSession());
	}

	/**
	 * @return the responses
	 */
	public static HttpServletResponse getResponses() {
		return responses.get();
	}

	/**
	 * @param responses
	 *            the responses to set
	 */
	public static void setResponses(HttpServletResponse response) {
		responses.set(response);
	}

	public static void setSessions(HttpSession httpSession) {
		sessions.set(httpSession);
	}
	
	/**
	 * @return the sessions
	 */
	public static HttpSession getSessions() {
		return sessions.get();
	}

	/**
	 * 从线程中删除对应对象
	 */
	public static void remove() {
		requests.remove();
		responses.remove();
		sessions.remove();
	}
	
	/**
	 * 为当前session设置属性
	 * @param key
	 * @param value
	 */
	public static void setSessionAttr(String key, Object value) {
		HttpSession session = sessions.get();
		session.setAttribute(key, value);
	}
	
	/**
	 * 获取当前session中的值
	 * @param key
	 */
	public static Object getSessionAttr(String key) {
		HttpSession session = sessions.get();
		return session.getAttribute(key);
	}
	
	/**
	 * 删除当前session中的属性
	 * @param key
	 */
	public static void removeSessionAttr(String key) {
		HttpSession session = sessions.get();
		session.removeAttribute(key);
	}
	
	/**
	 * 获取当前请求中的cookie的值
	 * @param key
	 */
	public static String getCookie(String key) {
		
		if (null == key) {
			return null;
		}
		
		HttpServletRequest request = requests.get();
		Cookie[] cookies = request.getCookies();
		if (null == cookies || 0 == cookies.length) {
			return null;
		}
		
		for (Cookie cookie : cookies) {
			if (null == cookie) {
				continue;
			}
			
			if (StringUtils.equals(cookie.getName(), key)) {
				return cookie.getValue();
			}
		}
		
		return null;
	}
	
	/**
	 * 向当前响应中增加Cookie
	 * @param key
	 * @param value
	 * @param seconds 单位秒
	 * @param httpOnly 是否设置httpOnly
	 */
	public static void addCookie(String key, String value, int seconds, boolean httpOnly) {
		Cookie cookie = new Cookie(key, value);
		cookie.setPath(getContextPath());
		cookie.setMaxAge(seconds);
		cookie.setHttpOnly(httpOnly);
		HttpServletResponse response = responses.get();
		response.addCookie(cookie);
	}
	
	/**
	 * 向当前响应中增加Cookie, 默认7天, 并设置httpOnly
	 * @param key
	 * @param value
	 */
	public static void addCookie(String key, String value) {
		addCookie(key, value, 604800, true);
	}
	
	/**
	 * 获取当前项目的绝对路径 <br/>
	 * 例: /a/webapps/ROOT
	 * @return 结尾不带分隔符
	 */
	public static String getRealPath() {
		return getServletContext().getRealPath("");
	}
	
	/**
	 * 获取当前项目的项目名 <br/>
	 * 例: /ROOT
	 * @return 带分隔符前缀
	 */
	public static String getContextPath() {
		return getServletContext().getContextPath();
	}
	
	
	/**
	 * 获取当前用户
	 * @return
	 */
	public static Teacher getCurrentUser() {
		HttpSession session = getSessions();
		
		Object val = session.getAttribute(Constant.CURRENT_TEACHER);
		
		if (null == val) {
			return null;
		}
		
		return (Teacher) val; 
	}
	
	/**
	 * 获取当前用户的家目录
	 * /home/test
	 * @return
	 */
	public static String getHomePath() {
		return System.getProperty("user.home");
	}
	
	/**
	 * 获取用户IP地址
	 * @return
	 */
	public static String getUserIp() {
	    
	    HttpServletRequest req = requests.get();

	    if (null == req) {
	        return null;
	    }
	    
	    String ipAddress = req.getHeader("x-forwarded-for");
	    
	    // 获取代理ip列表不为空，且不为unknown
	    if (StringUtils.isNotEmpty(ipAddress) && !StringUtils.equals("unknown", ipAddress)) {
	        return ipAddress;
	    }
	    
	    return req.getRemoteAddr();
	}
}
